<?php

namespace App\Http\Controllers\Api;

use App\Services\Api\UserAuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends ApiBaseController
{
    protected $userAuthService;

    public function __construct(UserAuthService $userAuthService)
    {
        $this->userAuthService = $userAuthService;
    }

    /**
     * 小程序用户登录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'code' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }
        $userId = auth('api')->id();
        if ($userId) {
            $token = auth('api')->getToken();
            if ($token) {
                $payload = JWTAuth::setToken($token)->getPayload();
                $exp = $payload->get('exp');
                $now = time();
                if ($exp - $now < 7200) {
                    // token 剩余时间小于 7200 秒，重新登录
                    $data = $this->userAuthService->login($request->all());
                    return $this->success($data);
                }
            }
            return $this->success($this->userAuthService->me($userId));
        }

        $data = $this->userAuthService->login($request->all());
        return $this->success($data);
    }

    /**
     * 退出登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();
        
        $data = [
            'success' => true
        ];
        return $this->success($data);
    }

    /**
     * 刷新token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->success($this->userAuthService->refresh());
    }
}